package com.tpv.tv.lib.pdf;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import java.io.File;

public class PdfApi {
    private static final String TAG = "PdfApi";

    public static void openPdf(@Nullable Activity activity, @NonNull String filePath) {
        if(activity == null) return;
        Log.i(TAG, "filePath : " + filePath);
        if(TextUtils.isEmpty(filePath)) return;
        int index = filePath.lastIndexOf(".");
        if(index == -1) {
            Log.e(TAG, "Illegal file type");
            return;
        }
        String fileType = filePath.substring(index + 1);
        if(!"pdf".equalsIgnoreCase(fileType)) {
            Log.e(TAG, "Not a pdf file type");
            return;
        }

        File file = new File(filePath);
        Uri fileUri = FileProvider.getUriForFile(activity,
                "tpv.tv.lib.pdf.provider",  // 在 Manifest 中配置的 authorities
                file);
//        Uri uri = Uri.parse("file://" + filePath);
        Log.i(TAG, "uri : " + fileUri.toString());
//        String mimeType = "application/pdf";
        String mimeType = activity.getContentResolver().getType(fileUri);
        Log.i(TAG, "mimeType : " + mimeType);
        Intent intent = new Intent(activity, DocumentActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
        intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        // Grant URI permissions to external apps
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(fileUri, mimeType);
        intent.putExtra(activity.getComponentName().getPackageName()
                + ".ReturnTo" + activity.getComponentName().getClassName().substring(activity.getComponentName().getClassName().lastIndexOf(".") + 1), 1);
        activity.startActivity(intent);
    }
}
